﻿import 'package:azring/pages/login/page/sms_login_view.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'package:azring/common/langs/text_key.dart';
import 'package:azring/common/res/gaps.dart';
import 'package:azring/common/utils/change_notifier_manage.dart';
import 'package:azring/common/utils/keyboard_util.dart';
import 'package:azring/core/services/storage_service.dart';
import 'package:azring/pages/login/login/login_logic.dart';
import 'package:azring/pages/login/login/login_state.dart';
import 'package:azring/widget/my_scroll_view.dart';

import '../login_router.dart';
import 'register_view.dart';

/// design/1注册登录/index.html
class LoginView extends StatefulWidget {
  const LoginView({super.key});

  @override
  _LoginViewState createState() => _LoginViewState();
}

class _LoginViewState extends State<LoginView>
    with ChangeNotifierMixin<LoginView>, TickerProviderStateMixin {
  //定义一个Logic
  final TextEditingController _nameLogic = TextEditingController();
  final TextEditingController _passwordLogic = TextEditingController();
  final FocusNode _nodeText1 = FocusNode();
  final FocusNode _nodeText2 = FocusNode();
  bool _clickable = false;
  bool _agreeTerms = false;
  late TabController _tabLogic;
  final LoginLogic logic = Get.put(LoginLogic());
  final LoginState state = Get.find<LoginLogic>().state;

  // 登录类型：true为密码登录，false为验证码登录
  bool _isPasswordLogin = true;

  // 密码可见性
  bool _obscurePassword = true;

  Map<ChangeNotifier, List<VoidCallback>?>? changeNotifier() {
    final List<VoidCallback> callbacks = <VoidCallback>[_verify];
    return <ChangeNotifier, List<VoidCallback>?>{
      _nameLogic: callbacks,
      _passwordLogic: callbacks,
      _nodeText1: null,
      _nodeText2: null,
    };
  }

  @override
  void initState() {
    super.initState();
    _tabLogic = TabController(length: 2, vsync: this);
    _nameLogic.text = StorageService.to.getUserName() ?? '';

    // 添加焦点监听器
    _nodeText1.addListener(_onFocusChange1);
    _nodeText2.addListener(_onFocusChange2);
  }

  void _onFocusChange1() {
    if (mounted) {
      setState(() {
        // 触发UI更新以显示正确的边框颜色
        print('焦点变化1: ${_nodeText1.hasFocus}');
      });
    }
  }

  void _onFocusChange2() {
    if (mounted) {
      setState(() {
        // 触发UI更新以显示正确的边框颜色
        print('焦点变化2: ${_nodeText2.hasFocus}');
      });
    }
  }

  @override
  void dispose() {
    _tabLogic.dispose();
    _nodeText1.removeListener(_onFocusChange1);
    _nodeText2.removeListener(_onFocusChange2);
    super.dispose();
  }

  void _verify() {
    final String name = _nameLogic.text;
    final String password = _passwordLogic.text;
    bool clickable = true;
    if (name.isEmpty || name.length < 4) {
      clickable = false;
    }
    if (password.isEmpty || password.length < 6) {
      clickable = false;
    }
    if (!_agreeTerms) {
      clickable = false;
    }

    /// 状态不一样再刷新，避免不必要的setState
    if (clickable != _clickable) {
      setState(() {
        _clickable = clickable;
      });
    }
  }

  void _login() {
    logic.requestData(
        username: _nameLogic.value.text, password: _passwordLogic.value.text);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        elevation: 0,
        systemOverlayStyle: SystemUiOverlayStyle.light,
        leading: null,
        automaticallyImplyLeading: false,
        bottom: TabBar(
          controller: _tabLogic,
          indicator: const UnderlineTabIndicator(
            borderSide: BorderSide(
              width: 2,
              color: Color(0xffF46425),
            ),
            insets: EdgeInsets.symmetric(horizontal: 40),
          ),
          labelColor: const Color(0xffF46425),
          unselectedLabelColor: Colors.white,
          labelStyle: const TextStyle(
            fontSize: 20,
            fontWeight: FontWeight.w500,
          ),
          unselectedLabelStyle: const TextStyle(
            fontSize: 20,
            fontWeight: FontWeight.w500,
          ),
          tabs: [
            Tab(text: TextKey.loginButton.tr),
            Tab(text: TextKey.register.tr),
          ],
        ),
      ),
      body: TabBarView(
        controller: _tabLogic,
        children: [
          _buildLoginTab(),
          const RegisterView(),
        ],
      ),
    );
  }

  // 构建登录标签页
  Widget _buildLoginTab() {
    return SafeArea(
      child: MyScrollView(
        keyboardConfig: KeyboardUtil.getKeyboardActionsConfig(
            context, <FocusNode>[_nodeText1, _nodeText2]),
        padding: const EdgeInsets.only(left: 16.0, right: 16.0, top: 16.0),
        children: _buildLoginBody,
      ),
    );
  }

  /// 构建登录页面主体内容
  List<Widget> get _buildLoginBody {
    if (_isPasswordLogin) {
      return _buildPasswordLoginBody;
    }
    return <Widget>[
      SMSLoginView(
        onSwitchToPasswordLogin: () {
          setState(() {
            _isPasswordLogin = true;
          });
        },
      )
    ];
  }

  List<Widget> get _buildPasswordLoginBody => <Widget>[
        Gaps.vGap21,
        // 输入框区域
        _buildInputSection(),
        Gaps.vGap21,
        // 按钮区域
        _buildButtonSection(),
        Gaps.vGap35,
        // 同意条款
        _buildTermsSection(),
        SizedBox(height: 140.h),
        // 登录按钮
        _buildLoginButton(),
      ];

  // 构建输入框区域
  Widget _buildInputSection() {
    return Column(
      children: [
        Container(
          height: 56.h,
          decoration: BoxDecoration(
            color: const Color(0xFF282528),
            borderRadius: BorderRadius.circular(12.r),
            border: Border.all(
              color: _nodeText1.hasFocus
                  ? const Color(0xffF45757)
                  : Colors.transparent,
              width: 0.5.w,
            ),
          ),
          child: TextField(
            focusNode: _nodeText1,
            controller: _nameLogic,
            style: const TextStyle(color: Colors.white, fontSize: 14),
            keyboardType: TextInputType.emailAddress,
            textAlignVertical: TextAlignVertical.center,
            onTap: () {
              setState(() {
                // 确保焦点变化时更新UI
              });
            },
            decoration: InputDecoration(
              hintText: TextKey.inputPhoneOrEmail.tr,
              hintStyle: const TextStyle(color: Colors.white, fontSize: 14),
              border: InputBorder.none,
              contentPadding:
                  const EdgeInsets.symmetric(horizontal: 25, vertical: 18),
            ),
          ),
        ),
        Gaps.vGap18,
        Container(
          height: 56.h,
          decoration: BoxDecoration(
            color: const Color(0xFF282528),
            borderRadius: BorderRadius.circular(12.r),
            border: Border.all(
              color: _nodeText2.hasFocus
                  ? const Color(0xffF46425)
                  : Colors.transparent,
              width: 0.5.w,
            ),
          ),
          child: TextField(
            focusNode: _nodeText2,
            controller: _passwordLogic,
            style: const TextStyle(color: Colors.white, fontSize: 14),
            obscureText: _obscurePassword,
            textAlignVertical: TextAlignVertical.center,
            onTap: () {
              setState(() {
                // 确保焦点变化时更新UI
              });
            },
            decoration: InputDecoration(
              hintText: TextKey.inputPassword.tr,
              hintStyle: const TextStyle(color: Colors.white, fontSize: 14),
              border: InputBorder.none,
              contentPadding:
                  const EdgeInsets.symmetric(horizontal: 25, vertical: 18),
              suffixIcon: GestureDetector(
                onTap: () {
                  setState(() {
                    _obscurePassword = !_obscurePassword;
                  });
                },
                child: Icon(
                  _obscurePassword ? Icons.visibility_off : Icons.visibility,
                  color: const Color(0xFF666666),
                  size: 20,
                ),
              ),
            ),
          ),
        ),
      ],
    );
  }

  // 构建按钮区域
  Widget _buildButtonSection() {
    return Row(
      children: [
        const Spacer(),
        GestureDetector(
          onTap: () {
            Get.toNamed(LoginRouter.resetPasswordPage);
          },
          child: Container(
            width: 80.w,
            height: 32.h,
            decoration: BoxDecoration(
              border: Border.all(color: const Color(0xffF46425)),
              borderRadius: BorderRadius.circular(18.r),
            ),
            child: Center(
              child: Text(
                TextKey.forgotPassword.tr,
                style: TextStyle(
                  color: Color(0xffF46425),
                  fontSize: 14.sp,
                  fontWeight: FontWeight.w300,
                ),
              ),
            ),
          ),
        ),
        Gaps.hGap10,
        GestureDetector(
          onTap: () {
            setState(() {
              _isPasswordLogin = false;
            });
          },
          child: Container(
            width: 99.w,
            height: 32.h,
            decoration: BoxDecoration(
              color: const Color(0xffF46425).withOpacity(0.9),
              borderRadius: BorderRadius.circular(18),
            ),
            child: Center(
              child: Text(
                TextKey.loginWithSMS.tr,
                style: TextStyle(
                  color: Colors.white.withOpacity(0.6),
                  fontSize: 14.sp,
                  fontWeight: FontWeight.w300,
                ),
              ),
            ),
          ),
        ),
      ],
    );
  }

  // 构建同意条款区域
  Widget _buildTermsSection() {
    return Row(
      children: [
        Gaps.hGap16,
        GestureDetector(
          onTap: () {
            setState(() {
              _agreeTerms = !_agreeTerms;
              _verify();
            });
          },
          child: Container(
            width: 14.w,
            height: 14.h,
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              color: _agreeTerms ? const Color(0xffF46425) : Colors.transparent,
              border: Border.all(
                color: _agreeTerms
                    ? const Color(0xffF46425)
                    : const Color(0xFF666666),
                width: 1,
              ),
            ),
            child: _agreeTerms
                ? const Icon(
                    Icons.check,
                    color: Colors.white,
                    size: 14,
                  )
                : null,
          ),
        ),
        Gaps.hGap8,
        Expanded(
            child: RichText(
          text: TextSpan(
            children: [
              TextSpan(
                text: TextKey.agreeTerms.tr, // "我已阅读并同意"
                style: TextStyle(color: Colors.white),
              ),
              TextSpan(
                text: TextKey.terms.tr, // "使用条款"
                style: TextStyle(color: Color(0xffF46425)),
                recognizer: TapGestureRecognizer()
                  ..onTap = () {
                    // 处理使用条款点击
                  },
              ),
              TextSpan(
                text: TextKey.and.tr, // "和"
                style: TextStyle(color: Colors.white),
              ),
              TextSpan(
                text: TextKey.privacy.tr, // "隐私政策"
                style: const TextStyle(color: Color(0xffF46425)),
                recognizer: TapGestureRecognizer()
                  ..onTap = () {
                    // 处理隐私政策点击
                  },
              ),
            ],
          ),
        )),
      ],
    );
  }

  // 构建登录按钮
  Widget _buildLoginButton() {
    return Container(
      width: double.infinity,
      height: 56.h,
      decoration: BoxDecoration(
        color: _clickable
            ? const Color(0xffF46425)
            : const Color(0xffF46425).withOpacity(0.5),
        borderRadius: BorderRadius.circular(999.r),
      ),
      child: Material(
        color: Colors.transparent,
        child: InkWell(
          onTap: _clickable ? _login : null,
          borderRadius: BorderRadius.circular(999.r),
          child: Center(
            child: Text(
              TextKey.loginButton.tr,
              style: TextStyle(
                color:
                    _clickable ? Colors.white : Colors.white.withOpacity(0.5),
                fontSize: 16.sp,
                fontWeight: FontWeight.w500,
              ),
            ),
          ),
        ),
      ),
    );
  }
}
